package com.example.baguwen.service.impl;

import com.example.baguwen.dto.UserLoginDTO;
import com.example.baguwen.dto.UserRegisterDTO;
import com.example.baguwen.entity.User;
import com.example.baguwen.repository.UserRepository;
import com.example.baguwen.service.UserService;
import com.example.baguwen.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.persistence.EntityNotFoundException;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;
    
    // 简单的内存token存储，实际应用中应该使用Redis或其他缓存
    private static final Map<String, Long> tokenStorage = new HashMap<>();
    
    @PostConstruct
    public void init() {
        // 检查是否已存在测试用户
        if (!userRepository.existsByUsername("admin")) {
            // 创建测试用户
            User admin = new User();
            admin.setUsername("admin");
            admin.setPassword("123456"); // 密码加密
            admin.setNickname("管理员");
            userRepository.save(admin);
            System.out.println("已创建测试用户: admin/123456");
        } else {
            System.out.println("测试用户admin已存在");
        }
    }
    
    @Override
    @Transactional
    public UserVO register(UserRegisterDTO registerDTO) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(registerDTO.getUsername())) {
            throw new IllegalStateException("用户名已存在");
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(registerDTO.getPassword()); // 密码加密
        user.setNickname(registerDTO.getNickname());
        
        // 保存用户
        user = userRepository.save(user);
        
        // 生成token
        String token = generateToken();
        tokenStorage.put(token, user.getId());
        
        // 转换为VO
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setToken(token);
        
        return userVO;
    }

    @Override
    public UserVO login(UserLoginDTO loginDTO) {
        // 打印登录信息
        System.out.println("尝试登录: " + loginDTO.getUsername() + "/" + loginDTO.getPassword());
        
        // 查找用户
        User user = userRepository.findByUsername(loginDTO.getUsername())
                .orElseThrow(() -> new EntityNotFoundException("用户不存在"));
        
        // 验证密码
        boolean equals = loginDTO.getPassword().equals(user.getPassword());
        System.out.println("密码验证: " + (equals ? "成功" : "失败"));
        
        if (!equals) {
            throw new IllegalStateException("密码错误");
        }
        
        // 生成token
        String token = generateToken();
        tokenStorage.put(token, user.getId());
        
        // 转换为VO
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setToken(token);
        
        return userVO;
    }

    @Override
    public UserVO getCurrentUser(String token) {
        Long userId = tokenStorage.get(token);
        if (userId == null) {
            throw new IllegalStateException("无效的token或已过期");
        }
        
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new EntityNotFoundException("用户不存在"));
        
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setToken(token);
        
        return userVO;
    }

    @Override
    public boolean isUsernameAvailable(String username) {
        return !userRepository.existsByUsername(username);
    }
    
    @Override
    public Long getCurrentUserId() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        Long userId = tokenStorage.get(token);
        if (userId == null) {
            throw new IllegalStateException("用户未登录");
        }
        
        return userId;
    }
    
    /**
     * 生成随机token
     */
    private String generateToken() {
        return UUID.randomUUID().toString().replace("-", "");
    }
} 